package com.atlassianstudio.confluence.htmldiff.actions;

import com.atlassian.confluence.pages.AbstractPage;
import com.atlassian.confluence.pages.actions.AbstractDiffPagesAction;
import com.atlassianstudio.confluence.htmldiff.Util;

public class DiffPagesByVersionAction extends AbstractDiffPagesAction {

    public DiffPagesByVersionAction() {
    }

    public void validate() {
        super.validate();
        if (originalVersion < 1 || revisedVersion < 1)
            addActionError(getText("error.must.specify.two.versions"));
    }

    public void setOriginalVersion(int originalVersion) {
        this.originalVersion = originalVersion;
    }

    public void setRevisedVersion(int revisedVersion) {
        this.revisedVersion = revisedVersion;
    }

    public AbstractPage getOriginalPage() {
        if (originalPage == null && originalVersion != 0)
            originalPage = (AbstractPage) pageManager.getOtherVersion(getPage(), originalVersion);
        return originalPage;
    }

    public AbstractPage getRevisedPage() {
        if (revisedPage == null && revisedVersion != 0)
            revisedPage = (AbstractPage) pageManager.getOtherVersion(getPage(), revisedVersion);
        return revisedPage;
    }

    public void setSelectedPageVersions(String selectedPageVersions[]) {
        if (selectedPageVersions.length == 2) {
            int version1 = Integer.parseInt(selectedPageVersions[0]);
            int version2 = Integer.parseInt(selectedPageVersions[1]);
            setOriginalVersion(Math.min(version1, version2));
            setRevisedVersion(Math.max(version1, version2));
        }
    }

    public String execute() throws Exception {
        validate();
        if (originalVersion < 1 || revisedVersion < 1) {
            return "error";
        } else {
            return super.execute();
        }
    }

    public void setSubmit(String submit) {
        this.html = (submit != null && submit.endsWith("HTML)"));
    }

    public boolean getHtml() {
        return this.html;
    }

    public String getDiff() {
        if (this.html) {
            try {
                return Util.diffHTML(wikiStyleRenderer.convertWikiToXHtml(getOriginalPage().toPageContext(), getOriginalPage().getContent()), wikiStyleRenderer.convertWikiToXHtml(getRevisedPage().toPageContext(), getRevisedPage().getContent()));
            } catch (Exception e) {
//                e.printStackTrace();
                return super.getDiff();
            }
        } else {
            return super.getDiff();
        }
    }

    private boolean html = false;
    private String submit;
    private int originalVersion, revisedVersion;
    private AbstractPage revisedPage;
}